package com.dailyblue.java.project.smbms.order.service.impl;

import com.dailyblue.java.commons.util.JsonResult;
import com.dailyblue.java.commons.util.ResultTool;
import com.dailyblue.java.project.smbms.order.feign.UserFeign;
import com.dailyblue.java.project.smbms.order.mapper.OrderMapper;
import com.dailyblue.java.project.smbms.order.service.OrderService;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
public class OrderServiceImpl implements OrderService {
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private UserFeign userFeign;
    @Resource
    private RocketMQTemplate rocketMQTemplate;

    @Transactional(rollbackFor = Exception.class)
    public JsonResult generateOrder(int aid, String payId, String token) {
        // 1.订单概述
        orderMapper.saveOrderSummary(aid, payId);
        HashOperations hash = stringRedisTemplate.opsForHash();
        String userId = getUserIdByToken(token);
        // 获取到指定用户的所有购物车信息
        Map<String, String> map = hash.entries("cart:" + userId);
        Set<String> set = map.keySet();
        for (String s : set) {
            int goodsId = Integer.parseInt(s);
            int num = Integer.parseInt(map.get(s));
            // 2.订单详情
            orderMapper.saveOrderDetails(payId, goodsId, num);
            // 3.向rocketMQ中生产一笔消息
            rocketMQTemplate.syncSend("STOCK:UPDATE", goodsId + "," + num);
            // 4.清除购物车
            hash.delete("cart:" + userId, goodsId + "");
        }
        return ResultTool.success();
    }

    private String getUserIdByToken(String token) {
        JsonResult result = userFeign.findUserIdByToken(token);
        if (!result.getSuccess()) {
            return null;
        }
        return result.getData().toString();
    }
}
